<template>
  <div class="search-container">
    <form action="/">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isShowResult = false"
      />
    </form>

    <search-result 
      v-if="isShowResult" 
      :q="searchText"
    />

    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search-item="onSearch"
    />

    <search-history 
      v-else
      :searchHistories="searchHistories"
      @clearhistory="searchHistories = []"
      @go-resut="onSearch"
    />

  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
import {setItem, getItem} from '@/utils/storage'

export default {
  name: 'searchBox',
  data () {
    return {
      searchText: '',
      isShowResult: false,
      searchHistories: getItem('searchHistories') || []
    }
  },
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  methods: {
    onSearch (val) {
      this.searchText = val
      this.isShowResult = true

      const index = this.searchHistories.indexOf(val)
      if (index !== -1) {
        this.searchHistories.splice(index, 1)
      }
      this.searchHistories.unshift(val)
    },
    onCancel () {
      this.isShowResult = false
      this.$toast('取消')
    }
  },
  watch: {
    searchHistories(val) {
      setItem('searchHistories', val)
    }
  }
}
</script>

<style lang="less" scoped>
.search-container{
  padding-top: 106px;
  .van-search {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
  }
}
</style>
